//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.config.WechatConfig;
import com.thoughtworks.xstream.XStream;
import com.util.HttpClientUtil;
import com.util.VerificationCodeManager;
import com.util.WxMessageUtil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping({"/WeChat"})
@Component
public class WxcharController {

    Map<String, String> code1 = new HashMap<>();

    private static final Logger log = LoggerFactory.getLogger(WxcharController.class);
    private String FromUserName = "o40Hd6flvPk2bVkDBe6Zr0zbfVBo";
    private String Event;

    @Autowired
    private WechatConfig wechatConfig;

    @Autowired
    private VerificationCodeManager verificationCodeManager;


    public WxcharController() {
    }

    @GetMapping({"/AP"})
    public String WeiXin(String signature, String timestamp, String nonce, String echostr) {
        String token = "GaoLin";
        List<String> list = Arrays.asList(token, timestamp, nonce);
        Collections.sort(list);
        StringBuilder stringBuilder = new StringBuilder();
        Iterator var8 = list.iterator();

        while (var8.hasNext()) {
            String s = (String) var8.next();
            stringBuilder.append(s);
        }

        try {
            MessageDigest instance = MessageDigest.getInstance("sha1");
            byte[] digest = instance.digest(stringBuilder.toString().getBytes());
            StringBuilder sum = new StringBuilder();
            byte[] bytes = digest;
            int di = digest.length;
            for (int i = 0; i < di; i++) {
                byte b = bytes[i];
                sum.append(Integer.toHexString(b >> 4 & 15));
                sum.append(Integer.toHexString(b & 15));
            }

            if (!StrUtil.isEmptyIfStr(signature) && signature.equals(sum.toString())) {
                return echostr;
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;
    }

    @PostMapping({"/AP"})
    public String receiveMessage(HttpServletRequest request) throws IOException {
        try {
            String dynamicCode = verificationCodeManager.generateCode();
            Map<String, String> map = WxMessageUtil.xmlToMap(request);
            this.Event = (String) map.get("Event");
            this.FromUserName = (String) map.get("FromUserName");
            String Ticket = map.get("Ticket");
            String Content = map.get("Content");
            System.out.println(this.Event);
            System.out.println(this.FromUserName);
            System.out.println(map);
            String msgType = (String) map.get("MsgType");
            XStream stream = new XStream();

            if (Event != null) {
                code1.put(Ticket, FromUserName);
                code1.put(FromUserName + "1", Event);
            } else if (Content != null) {
                code1.put(FromUserName, dynamicCode);
            }


            System.out.println(code1);
            switch (msgType) {
                case "link":
                    break;
                case "text":
                    verificationCodeManager.sendCodeToUser(FromUserName, dynamicCode);
                    break;
            }


        } catch (DocumentException e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    @GetMapping({"/access"})
    public String getWxCode() {
        String qrcodeUrl = "";
        String baseUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
        String url = String.format(baseUrl, this.wechatConfig.getAppid(), this.wechatConfig.getSecret());

        try {
            URL oracle = new URL(url);
            URLConnection conn = oracle.openConnection();
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine = null;

            while ((inputLine = br.readLine()) != null) {
                System.out.println(inputLine);
                this.wechatConfig.setAccess_token(inputLine.substring(17, 153));
                System.out.println(this.wechatConfig.getAccess_token());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            String accessToken = this.wechatConfig.getAccess_token();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("expire_seconds", 2592000);
            jsonObject.put("action_name", "QR_STR_SCENE");
            JSONObject actionInfo = new JSONObject();
            JSONObject scene = new JSONObject();
            scene.put("scene_str", "第三方登录");
            actionInfo.put("scene", scene);
            jsonObject.put("action_info", actionInfo);
            String Vurl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
            String result = HttpClientUtil.doPostJson(Vurl, jsonObject.toJSONString());
            JSONObject resultJson = JSONObject.parseObject(result);
            String ticket = resultJson.getString("ticket");
            Integer expire_seconds = resultJson.getInteger("expire_seconds");
            qrcodeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + URLEncoder.encode(ticket, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        System.out.println(qrcodeUrl);
        return qrcodeUrl;
    }

    @GetMapping({"/login"})
    public String WeChatLogin(@RequestParam(value = "code", required = false, defaultValue = "") String code,
                              @RequestParam(value = "Ticket", required = false, defaultValue = "") String Ticket,
                              HttpServletResponse response,
                              HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();

        //获取用户信息
        String tk = code1.get(Ticket);
        String et = code1.get(Ticket + "1");
        String cd = code1.get(tk);

        if (("SCAN".equals(et) || "subscribe".equals(et)) && cd.equals(code)) {
            if (cookies == null) {
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                System.out.println(uuid);
                System.out.println(uuid);
                Cookie cookie = new Cookie("username", "Wx_" + uuid);
                cookie.setMaxAge(999999999);
                response.addCookie(cookie);
                return "Username is changed!";
            } else if (cookies != null) {
                for (Cookie cookie : cookies) {
                    System.out.println("name:" + cookie.getName() + ",value:" + cookie.getValue());
                }
                return "";
            }

        } else if (("SCAN".equals(et) || "subscribe".equals(et)) && !cd.equals(code)) {
            return "验证码错误";

        } else if ((et == null || "unsubscribe".equals(et)) && cd.equals(code)) {
            return "扫描公众号失败，请再次扫描";
        }
        return "";
    }


}